import { useEffect, useMemo, useRef } from 'react';
import _ from 'lodash';
import moment from 'moment';
import { message, Modal, notification } from 'antd';
import { WithNormalRender } from "@ey-render/hoc-form";
import { getSubmitFormValues } from '@ey-utils/utils/formily-utils/getSubmitFormValues';
import { history } from 'umi';
import { onFieldChange, onFieldInit, onFieldMount, onFieldValueChange, onFormMount } from '@formily/core';
import { numberPage, archivesBoxCreate, archivesPageByBox } from './services';
import { Form } from '@formily/core/esm/models';
import components from "@/components/schema-form-render/schema-components-registed/components-biz";

const FileBoxCreate = () => {
  const billCodeRef = useRef<any>();
  const modalRef = useRef<any>();

  useEffect(() => {
    document.addEventListener('keydown', (e) => {
      if (e.code === 'Enter') {
        modalRef.current?.destroy?.();
      }
    })
  }, [])

  const handleBack = () => {
    return history.back();
  };

  const BillFormLayout = useMemo(() => {
    return WithNormalRender({
      filedConfig: {},
      components: {
        ...components,
      },
    });
  }, []);

  // 提交
  const submit = async ({ form }: any) => {
    const formValues = await getSubmitFormValues(form);

    if (formValues) {
      const params = {
        ...formValues,
        pageCode: 'ArcvFileBox_C',
      };
      const res: any = await archivesBoxCreate(params);

      const { success } = res || {};

      if (success) {
        handleBack();
      }

      return res;
    }

    return {
      success: false,
    };
  };

  const searchArchives = _.debounce(async (form: Form<any>, code: string) => {
    const { arcvItems, company } = form.values;

    if (!company) {
      message.error('请先选择归档公司');
      return;
    }

    const res: any = await archivesPageByBox({
      pageNo: 1,
      pageSize: 20,
      queryKeys: {
        arcvBizCode: code,
        arcvCompanyCode: company,
        pageCode: 'ArchivesManage_Items_L',
      },
    });

    if (res.success) {
      if (!res.result?.content?.length) {
        modalRef.current = Modal.confirm({
          title: `单据号 ${code} 对应的案件未达到归档状态`,
          cancelButtonProps: {style: { display: 'none' }},
          onOk: () => {
            form.setFieldState('billCode', (field: any) => {
              field.value = '';
              billCodeRef.current?.focus();
            })
          }
        })

        return;
      }

      let newArcvItems: any[] = [...arcvItems];
      let repeatArcvCodes: any[] = [];

      res.result.content.forEach((item: any) => {
        if (arcvItems.find((o: any) => item.arcvCode === o.arcvCode)) {
          repeatArcvCodes.push(item.arcvCode);
          return;
        }
        newArcvItems = [item, ...newArcvItems];
      })
      form.setValuesIn('arcvItems', newArcvItems);

      if (repeatArcvCodes.length > 0) {
        notification.warning({
          message: `案件业务单号 ${code} 下的案件存在重复`,
          duration: 5
        });
      }
    }
    form.setValuesIn('billCode', undefined);
  }, 500);

  return (
    <BillFormLayout
      anchor
      type="NORMAL"
      pageCode="ArcvFileBox_C"
      events={{
        submit,
      }}
      formConfigs={{
        effects: () => {
          onFormMount((form) => {
            form.setValuesIn('createTime', moment());
            form.setFieldState('arcvItemsInfo', state => {
              state.visible = false;
            })
          });
          onFieldInit('billCode', (field: any, form) => {
            field.componentProps.onInput = async (e: any) => {
              const code = e.target.value;

              searchArchives(form, code);
            };
            field.componentProps.ref = billCodeRef;
          });
          onFieldMount('arcvItems', (field, form) => {
            field.componentProps = {
              ...field.componentProps,
              checkClickFn: () => {
                if (!form.values?.company) {
                  message.error('请先选择归档公司');
                  return false;
                }
                return true;
              }
            }
          })
          onFieldChange('belongCo', (field: any, form) => {
            form.setFieldState('whseCode', (st) => {
              st.componentProps = _.merge(st.componentProps, {
                disabled: !field.value,
                api: {
                  params: {
                    queryKeys: {
                      belongCo: field.value,
                      pageCode: 'ArcvWhse_L',
                    },
                  },
                },
              });
            });
            form.setFieldState('cbntCode', st => {
              st.componentProps = _.merge(st.componentProps, {
                disabled: !field.value,
                api: {
                  params: {
                    queryKeys: {
                      belongCo: field.value
                    }
                  }
                }
              })
            })
            if (!field.modified) return;

            const { billCode } = form.values;

            !!billCode && searchArchives(form, billCode);
            form.setValuesIn('whseCode', undefined);
            form.setValuesIn('cbntCode', undefined);
            form.setValuesIn('whseCodeName', undefined);
            form.setValuesIn('belongCoName', field.inputValues?.[1]?.name);
          });
          onFieldChange('whseCode', (field: any, form) => {
            form.setFieldState('cbntCode', st => {
              st.componentProps = _.merge(st.componentProps, {
                disabled: !field.value,
                api: {
                  params: {
                    queryKeys: {
                      whseCode: field.value
                    }
                  }
                }
              })
              if (!field.modified) return;
              form.setValuesIn('cbntCode', undefined);
            })
          });
          onFieldValueChange('arcvType', (field, form) => {
            if (!field.modified) return;
            form.setValuesIn('protctYears', field.inputValues?.[1]?.triggerNode.props.protctYears);
            form.setValuesIn('arcvTypeName', field.inputValues?.[2]?.[0]);
          });
          onFieldValueChange('coCode', async (field, form) => {
            if (!field.modified) return;
            form.setValuesIn('coName', field.inputValues?.[1]?.name);

            const res: any = await numberPage({
              pageNo: 1,
              pageSize: 1,
              queryKeys: {
                company: field.value,
                pageCode: 'ArcvNumber_L',
              },
            });
            const content = res.result?.content || [];

            form.setValuesIn('qzCode', content[0]?.code);
            form.setFieldState('arcvItems', (state: any) => {
              state.componentProps = {
                ...state.componentProps,
                extraPrams: {
                  arcvCompanyCode: field.value
                },
              }
            })
          });
        },
      }}
      filedConfig={{}}
    />
  );
};

export default FileBoxCreate;
